<template>
  <div class="app-container">
    <div>
    <div class="cont-editor">
      <div>
        园所介绍：
      </div>
      <quill-editor
        ref="myQuillEditor"
        v-model="content"
        class="ql-editor"
        :options="editorOption"
        @blur="onEditorBlur($event)"
        @focus="onEditorFocus($event)"
        @change="onEditorChange($event)"
      />
    </div>
    <div  style="display: flex;justify-content:flex-end;align-items: center;">
        <el-button size="small" type="primary" @click="save">保存</el-button>
    </div>
  </div>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import { getSchoolDesc,saveSchoolDesc,uploadBase64 } from '@/api/homeSystem/ysjcxxgl'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
export default {
  components: {
    quillEditor
  },
  data() {
    return {
      content: '', // 双向数据绑定数据
      loading: null,
      imgBlob: [],
      imgSuccArr: [1],
      imgArr: [],
      imgValue: null,
      isLoading: false,
      imgError: [],
      sizeTotal: 0,
      sizeJ: 0,
      fileId: "",
      fileName: "",
      isDisabled:true,
      editorOption: {
        placeholder: '请输入',
        theme: 'snow',
        readOnly:true,
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            ['blockquote', 'code-block'], // 引用  代码块
            [{ header: 1 }, { header: 2 }], // 1、2 级标题
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            [{ script: 'sub' }, { script: 'super' }], // 上标/下标
            [{ indent: '-1' }, { indent: '+1' }], // 缩进
            [{ direction: 'rtl' }], // 文本方向
            [{ size: ['12px', false, '16px', '18px', '20px', '30px'] }], // 字体大小
            [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
            [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
            [
              {
                font: [
                  false,
                  'SimSun',
                  'SimHei',
                  'Microsoft-YaHei',
                  'KaiTi',
                  'FangSong',
                  'Arial'
                ]
              }
            ], // 字体种类
            [{ align: [] }], // 对齐方式
            ['clean'], // 清除文本格式
            ['link', 'image'] // 链接、图片
          ]
        }
      }
    }
  },
  created(){
    // this.fileId = this.$route.query.id
    // this.fileName = this.$route.query.name
  },
  mounted(){
    this.queryFileContent()
  },
  watch: {
    imgSuccArr: {
      handler(val) {
        if (val.length === this.imgBlob.length && this.isLoading) {
          this.content = this.imgArr.join('"')
          // this.$set(this.imgValue, 'deviationDescription', this.imgArr.join('"'))
          this.loading = false
          this.isLoading = false
          !this.imgError.length && this.$message.success('图片处理完成！')
          console.timeEnd('处理图片')
          console.log(this.sizeTotal, this.sizeJ,'this.content',this.content)
        }
      },
      deep: true
    }
  },
  methods: {
    // 保存
    async save(){
      const obj = {
        schoolCode: this.$store.getters.schoolCode,
        description: this.content
      }
      const res = await saveSchoolDesc(obj)
      const { code, data, message } = res
      if (code === 200) {
        this.$message.success('保存完成！')
      } else {
        this.$message.error(message)
      }
    },
    async queryFileContent(){
      const res = await getSchoolDesc(this.$store.getters.schoolCode )
      const { code, data, message } = res
      if (code === 200) {
        this.content = data
      } else {
        this.$message.error(message)
      }
    },
    cancel() {
      this.$router.go(-1)
    },
    // 失去焦点事件
    onEditorBlur(quill) {
      console.log('editor blur!', quill)
    },
    // 获得焦点事件
    onEditorFocus(quill) {
      console.log('editor focus!', quill)
    },
    // 准备富文本编辑器
    onEditorReady(quill) {
      console.log('editor ready!', quill)
    },
    // 内容改变事件
    onEditorChange({ quill, html, text }) {
      // console.log('editor change!', html)
      // console.log('process.env.VUE_APP_BASE_API',process.env.VUE_APP_BASE_API);
      let modifiedContent = html.replace(/(<img[^>]*src=")(images[^"]*)("[^>]*>)/g, function(match, p1, p2, p3) {
          return p1 + window.config.base_url+'/' + p2 + p3;
      });
      this.content = modifiedContent
      const str = this.content
      if (str.includes('data:image')) {
        this.sizeTotal = 0
        this.sizeJ = 0
        console.time('处理图片')
        this.imgBlob = []
        this.imgSuccArr = []
        this.imgError = []
        this.imgValue = this.editorValue
        const imgArr = str.split('<img')
        imgArr.forEach((v, i) => {
          if (v.includes('alt=') && v.includes('src=')) {
            this.$set(imgArr, i, "   width=\'50\'" + v)
          }
        })
        const newStr = imgArr.join('<img')
        const arr = newStr.split('"')
        let srcIndex
        arr.forEach((item, index) => {
          if (item.includes('blob:http')) {
            this.imgBlob.push(item)
            srcIndex = index
            const img = new Image()
            img.src = arr[srcIndex]
            img.onload = () => {
              this.isLoading = true
              this.getBase64(img, arr, index)
            }
          }

          if (item.includes('data:image')) {
            this.imgBlob.push(item)
            const img = new Image()
            srcIndex = index
            img.src = arr[srcIndex]
            this.isLoading = true
            this.getBase64(img, arr, index)
          }
        })
      }
    },
    getBase64(img, arr, index) {
      // console.log('img', img)
      img.onload = () => {
        const canvas = document.createElement('canvas')
        canvas.width = img.width
        canvas.height = img.height
        const ctx = canvas.getContext('2d')
        ctx.drawImage(img, 0, 0, img.width, img.height)
        const newCanvas = (canvas, size) => canvas.toDataURL('image/jpeg', size >= 1 && 0.4)
        const dataURL = newCanvas(canvas)
        console.log('newCanvas', dataURL)
        const totalBytes = new Blob([dataURL]).size
        const sizeInMB = totalBytes / (1024 * 1024)
        const dataURLNew = (sizeInMB >= 1) ? newCanvas(canvas, sizeInMB) : dataURL
        this.sizeTotal = this.sizeTotal + (dataURLNew.length / (1024 * 1024))
        console.log('this.sizeTotal',this.sizeTotal);
        this.sizeJ = this.sizeJ + sizeInMB
        const formData = new FormData()
        formData.append('base64Str', dataURLNew)
        const data = { base64Str: dataURLNew }

        this.uploadBaseImg(arr, index, { data, formData })
      }
    },
    async uploadBaseImg(arr, index, formData) {
      // formData.data.fileName =
      try {
        const res = await uploadBase64(formData.data)
        const flage = res.code === 200
        const data = flage ? res : ''
        console.log(res, '00000')
        this.loading = false
        this.$set(arr, index, data.url)
        this.imgArr = arr
        !flage && this.imgError.push(1)
        this.imgSuccArr.push(1)
      } catch (error) {
        this.imgError.push(1)
        this.imgSuccArr.push(1)
        this.$set(arr, index, '')
        this.imgArr = arr
        // this.$common.errorMessage(error)
      }
      console.log('this.imgSuccArr', this.imgArr)
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .ql-container.ql-snow{
  height: 200px!important;
}
::v-deep .ql-snow {
  .ql-editor {
    img{
      max-width: 10%;
    }
  }
}
</style>

